// 任务管理应用
class TaskManager {
    constructor() {
        this.tasks = JSON.parse(localStorage.getItem('tasks')) || [];
        this.currentFilter = 'all';
        this.initialize();
    }

    initialize() {
        this.bindEvents();
        this.renderTasks();
    }

    bindEvents() {
        // 表单提交事件
        document.getElementById('taskForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.addTask();
        });

        // 过滤器按钮事件
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.setFilter(e.target.dataset.filter);
            });
        });
    }

    addTask() {
        const titleInput = document.getElementById('taskTitle');
        const descriptionInput = document.getElementById('taskDescription');
        const prioritySelect = document.getElementById('taskPriority');

        const task = {
            id: Date.now(),
            title: titleInput.value.trim(),
            description: descriptionInput.value.trim(),
            priority: prioritySelect.value,
            completed: false,
            createdAt: new Date().toISOString()
        };

        if (task.title) {
            this.tasks.unshift(task);
            this.saveTasks();
            this.renderTasks();
            
            // 重置表单
            titleInput.value = '';
            descriptionInput.value = '';
            prioritySelect.value = 'medium';
            titleInput.focus();
        }
    }

    toggleTaskCompletion(taskId) {
        const task = this.tasks.find(t => t.id === taskId);
        if (task) {
            task.completed = !task.completed;
            this.saveTasks();
            this.renderTasks();
        }
    }

    deleteTask(taskId) {
        if (confirm('确定要删除这个任务吗？')) {
            this.tasks = this.tasks.filter(t => t.id !== taskId);
            this.saveTasks();
            this.renderTasks();
        }
    }

    setFilter(filter) {
        this.currentFilter = filter;
        
        // 更新活动按钮样式
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.classList.remove('active');
            if (btn.dataset.filter === filter) {
                btn.classList.add('active');
            }
        });

        this.renderTasks();
    }

    getFilteredTasks() {
        switch (this.currentFilter) {
            case 'pending':
                return this.tasks.filter(task => !task.completed);
            case 'completed':
                return this.tasks.filter(task => task.completed);
            default:
                return this.tasks;
        }
    }

    renderTasks() {
        const tasksContainer = document.getElementById('taskList');
        const filteredTasks = this.getFilteredTasks();

        if (filteredTasks.length === 0) {
            tasksContainer.innerHTML = `
                <div class="empty-state">
                    <p>暂无任务</p>
                    <p>点击"添加任务"开始记录您的任务吧！</p>
                </div>
            `;
            return;
        }

        tasksContainer.innerHTML = filteredTasks.map(task => `
            <div class="task-item ${task.completed ? 'completed' : ''} priority-${task.priority}">
                <div class="task-header">
                    <h3 class="task-title">${this.escapeHtml(task.title)}</h3>
                    <span class="task-priority">${this.getPriorityLabel(task.priority)}</span>
                </div>
                ${task.description ? `<p class="task-description">${this.escapeHtml(task.description)}</p>` : ''}
                <div class="task-actions">
                    <button class="btn-complete" onclick="taskManager.toggleTaskCompletion(${task.id})">
                        ${task.completed ? '标记未完成' : '标记完成'}
                    </button>
                    <button class="btn-delete" onclick="taskManager.deleteTask(${task.id})">删除</button>
                </div>
            </div>
        `).join('');
    }

    getPriorityLabel(priority) {
        const labels = {
            'high': '高优先级',
            'medium': '中优先级',
            'low': '低优先级'
        };
        return labels[priority];
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(this.tasks));
    }
}

// 初始化应用
const taskManager = new TaskManager();